<?php

namespace GordenSong\Laravel\Providers;

use GordenSong\Laravel\Console\Command\GenerateValidatorCommand;
use GordenSong\Laravel\Support\Collection;
use GordenSong\Laravel\Support\Validator;
use GordenSong\Laravel\Utils\PathUtil;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Factory;

class LaravelValidatorServiceProvider extends ServiceProvider
{
	/**
	 * Indicates if loading of the provider is deferred.
	 *
	 * @var bool
	 */
	protected $defer = true;

	/**
	 * Register the service provider.
	 *
	 * @return void
	 */
	public function register()
	{
		//$this->app->bind('command.gs-validator.generate', function ($app) {
		//	return new GenerateValidatorCommand($app['files']);
		//});

		//$this->commands('command.gs-validator.generate');

		$this->mergeConfigFrom($this->configPath(), 'table-validator.php');
	}

	public function boot()
	{
		$configPath = $this->configPath();
		if (function_exists('config_path')) {
			$publishPath = config_path('table-validator.php');
		} else {
			$publishPath = base_path('config/table-validator.php');
		}
		$this->publishes([$configPath => $publishPath], 'config');

		$this->validatorBindValidateMethod();
	}

	protected function configPath(): string
	{
		$configPath = __DIR__ . '/../../config/table-validator.php';
		return PathUtil::crossPlatformPath($configPath);
	}

	/**
	 * Get the services provided by the provider.
	 *
	 * @return array
	 */
	public function provides(): array
	{
		return [
			'command.gs-validator.generate'
		];
	}

	protected function validatorBindValidateMethod(): void
	{
		Validator::macro('validate', function (array $data) {
			/** @var Factory $factory */
			$factory = app(Factory::class);

			/** @var Validator $this */
			return $factory->validate($data, $this->rules(), $this->messages(), $this->attributes());
		});

		Collection::macro('validate', function (array $data) {
			/** @var Factory $factory */
			$factory = app(Factory::class);

			/** @var Validator $this */
			return $factory->validate($data, $this->rules(), $this->messages(), $this->attributes());
		});
	}

}
